<template>
  <a-card>
    <a-spin :spinning="spinning" size="large">
      <a-form @submit="handleSubmit" :form="form" :labelCol="{ lg: { span: 5 }, sm: { span: 7 } }" :wrapperCol="{ lg: { span: 10 }, sm: { span: 17 } }">
        <a-form-item label="广告名称">
          <a-input
            v-decorator="['title', { rules: [{ required: true, max: 20, message: '请输入频道名称，不超过20个字符,不可输入符号！', whitespace: true, pattern: /^[\u4E00-\u9FA5A-Za-z0-9]+$/ }] }]"
            name="name"
            placeholder="最多可输入20个字"
            :max-length="20"
            autocomplete="off"
          />
        </a-form-item>
        <a-form-item label="投放时间" has-feedback>
          <a-range-picker
            style="width: 100%"
            :show-time="{ format: 'HH:mm:ss' }"
            format="YYYY-MM-DD HH:mm:ss"
            :placeholder="['开始时间', '结束时间']"
            v-decorator="['timePicker', { rules: [{ required: true, message: '请选择时间！' }] }]"
          />
        </a-form-item>
        <a-divider />

        <a-form-item label="投放平台">
          <a-select
            v-decorator="['platform', { rules: [{ required: true, message: '请选择!' }] }]"
            placeholder="请选择"
            :getPopupContainer="triggerNode => triggerNode.parentNode"
            @change="changeType"
          >
            <a-select-option value="1">小程序</a-select-option>
            <a-select-option value="2">导购</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="广告位">
          <a-select v-decorator="['place', { rules: [{ required: true, message: '请选择!' }] }]" placeholder="请选择" :getPopupContainer="triggerNode => triggerNode.parentNode">
            <a-select-option :value="6" v-if="flagType == 2">首页banner</a-select-option>
            <a-select-option :value="item.value * 1" v-for="(item, index) in advertLoc" :key="index" v-else>{{ item.text }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-model-item label="可见商家" v-if="flagType == 2">
          <a-select v-decorator="['merchantId', { rules: [{ required: true, message: '请选择!' }] }]" placeholder="请选择" :getPopupContainer="triggerNode => triggerNode.parentNode">
            <a-select-option value="0">不限</a-select-option>
            <a-select-option value="176">直营可见</a-select-option>
            <a-select-option value="1">经销可见</a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-item label="可见品牌" v-if="flagType == 2">
          <a-select v-decorator="['arcBrandId', { rules: [{ required: true, message: '请选择!' }] }]" placeholder="请选择" :getPopupContainer="triggerNode => triggerNode.parentNode">
            <a-select-option value="0">不限</a-select-option>
            <a-select-option :value="item.arcBrandId" v-for="item in brandList" :key="item.arcBrandId">
              {{ item.brandName }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <template>
          <a-form-item label="跳转类型">
            <a-select
              v-decorator="['skipType', { rules: [{ required: true, message: '请选择!' }] }]"
              placeholder="请选择"
              :getPopupContainer="triggerNode => triggerNode.parentNode"
              v-if="flagType == 2"
            >
              <a-select-option :value="5">自定义链接</a-select-option>
              <a-select-option :value="4">不跳转</a-select-option>
            </a-select>
            <a-select v-decorator="['skipType', { rules: [{ required: true, message: '请选择!' }] }]" placeholder="请选择" :getPopupContainer="triggerNode => triggerNode.parentNode" v-else>
              <a-select-option :value="item.value * 1" v-for="(item, index) in advertJumpUrl" :key="index">{{ item.text }}</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="小程序路径/h5链接">
            <a-input v-decorator="['skipUrl', { rules: [{ required: true }] }]" name="name" autocomplete="off" />
          </a-form-item>
          <a-form-item label="排序值">
            <a-input
              v-decorator="['priority', { rules: [{ required: true, pattern: /^[1-9]\d*$/, message: '请输入排序值！', whitespace: true }] }]"
              name="name"
              placeholder="填写数字"
              autocomplete="off"
            />
          </a-form-item>
          <a-form-item label="广告图" required>
            <JImageUpload :uploadParams="getUploadParams()" :isMultiple="false" :fileSize="0.512" :accept="'image/*'" @fileChange="fileChange" v-model="imgList"></JImageUpload>
            <div class="tip" v-show="tipsImg">请上传图片！</div>
            <p>
              图片小于512K，jpg、gif、png格式 <br />*新首页banner：1125x540px、信息流banner：500x720px、 订单页-悬浮窗：宽170px高自定、个人中心banner：1029x270px、
              BOX支付成功/申请退回banner：690x280px、 有搭支付成功banner：670x200px，主动要盒页banner：1125x180px
            </p>
          </a-form-item>
        </template>
        <a-divider />
        <a-form-item :wrapperCol="{ span: 24 }" style="text-align: center">
          <a-button htmlType="submit" type="primary">提交</a-button>
          <a-button style="margin-left: 8px" @click="handleBack">关闭</a-button>
        </a-form-item>
      </a-form>
    </a-spin>
  </a-card>
</template>
<script>
import moment from 'moment'
import 'moment/locale/zh-cn'
import JImageUpload from '@/components/qiniuUpload/JImageUpload.vue'
import globalData from '@/assets/js/common'
import { advertDetail, advertCreateOrUpdate } from '@/api/box/marketing'
import { initDictOptions, filterDictText } from '@/components/dict/JDictSelectUtil'
import { brandCondition } from '@/api/box/product'
import pick from 'lodash.pick'

export default {
  components: { JImageUpload },
  data() {
    return {
      moment,
      spinning: false,
      adverId: '',
      form: this.$form.createForm(this),
      beginDate: '',
      endDate: '',
      imgList: [],
      fileList: [],
      advertLoc: [],
      advertJumpUrl: [],
      tipsImg: false,
      brandList: [],
      flagType: 1
    }
  },
  created() {
    this.initDictConfig()
    this.fetchPathId()
    this.getCondition()
  },
  beforeRouteLeave(to, from, next) {
    this.$destroy()
    next()
  },
  methods: {
    changeType(e) {
      this.flagType = e
      console.log(this.form)
      this.form.resetFields('place')
      this.form.setFieldsValue({
        skipType: ''
      })
    },
    getCondition() {
      brandCondition().then(res => {
        if (res.code === 0) {
          this.brandList = res.data
        } else {
          this.$message.error(res.data.msg)
        }
      })
    },
    fetchPathId() {
      const id = this.$route.params.id
      if (id !== 'add') {
        this.adverId = id
        this.fetchData(id)
      }
    },
    // 初始化字典
    initDictConfig() {
      //初始化字典 - 广告位
      initDictOptions('advert_loc').then(res => {
        if (res.success) {
          this.advertLoc = res.result
        }
      })
      initDictOptions('advert_jump_url').then(res => {
        if (res.success) {
          this.advertJumpUrl = res.result
        }
      })
    },
    // 上传图片
    getUploadParams() {
      return { ...globalData.uploadParams }
    },
    fileChange(list) {
      console.log(list)
      this.fileList = list
    },
    fetchData(id) {
      this.spinning = true
      let self = this
      let params = {
        requestData: {
          id: id
        }
      }
      advertDetail(params)
        .then(res => {
          if (res.code === 0) {
            this.imgList = [res.data.imgUrl]
            let data = res.data
            this.flagType = data.platform == 2 ? 2 : 1

            data.timePicker = [moment(res.data.beginTime), moment(res.data.endTime)]
            this.$nextTick(() => {
              self.form.setFieldsValue(pick(data, 'title', 'platform', 'merchantId', 'arcBrandId', 'place', 'skipType', 'priority', 'timePicker', 'skipUrl'))
            })
          } else {
            this.$message.error(res.msg)
          }
          this.spinning = false
        })
        .catch(err => {
          console.log(err)
        })
    },
    handleSubmit(e) {
      e.preventDefault()
      this.tipsImg = false
      if (!this.fileList.length) this.tipsImg = true
      this.form.validateFields((err, values) => {
        // console.log(err)
        if (!err && !this.tipsImg) {
          // console.log('Received values of form: ', values)
          let formValues = {}
          for (let key in values) {
            if (key == 'timePicker') {
              formValues.beginTime = values.timePicker[0].format('YYYY-MM-DD HH:mm:ss')
              formValues.endTime = values.timePicker[1].format('YYYY-MM-DD HH:mm:ss')
            } else {
              formValues[key] = values[key]
            }
          }
          formValues.imgUrl = this.fileList[0].url
          formValues.merchantId = formValues.merchantId ? formValues.merchantId.toString() : ''
          if (this.adverId != '') formValues.id = this.adverId
          console.log(formValues)
          // return
          this.submitCreate(formValues)
        }
      })
    },
    submitCreate(d) {
      const data = {
        requestData: d
      }
      advertCreateOrUpdate(data)
        .then(res => {
          if (res.code === 0) {
            this.$message.success('编辑成功！')
            this.$router.back()
          } else {
            this.$message.error(res.msg)
          }
        })
        .catch(err => {
          console.log('submitCreate:' + err)
        })
    },
    handleBack() {
      this.$router.back()
    }
  }
}
</script>
<style scoped>
.icon-img {
  width: 86px;
  height: 86px;
  object-fit: scale-down;
}
.tip {
  color: #f5222d;
  line-height: 22px;
  margin-top: -8px;
}
</style>

